// 增强版游戏JavaScript代码
document.addEventListener('DOMContentLoaded', function() {
    // 游戏配置
    const gameConfig = {
        tutorialEnabled: true,
        soundEnabled: true,
        difficulty: 'normal', // easy, normal, hard
        showFPS: false
    };
    
    // 游戏统计数据
    const gameStats = {
        enemiesKilled: 0,
        highestWave: 0,
        towersBuilt: 0,
        towersUpgraded: 0,
        totalDamageDealt: 0,
        coinsEarned: 0,
        livesLost: 0,
        achievements: []
    };
    
    // 成就列表
    const achievements = [
        { id: 'first_blood', name: '首杀', description: '击败第一个敌人', unlocked: false },
        { id: 'tower_master', name: '建塔大师', description: '建造10座防御塔', unlocked: false },
        { id: 'wave_10', name: '十波坚守', description: '成功抵御10波敌人', unlocked: false },
        { id: 'no_loss', name: '完美防御', description: '不损失任何生命值通过5波', unlocked: false },
        { id: 'rich', name: '富可敌国', description: '拥有1000枚铜钱', unlocked: false },
        { id: 'sniper', name: '神射手', description: '使用连弩塔击杀50个敌人', unlocked: false },
        { id: 'flame_master', name: '烈焰大师', description: '使用烽火台造成1000点伤害', unlocked: false }
    ];
    
    // 获取DOM元素
    const enemiesKilledEl = document.getElementById('enemies-killed');
    const highestWaveEl = document.getElementById('highest-wave');
    const notificationEl = document.getElementById('notification');
    const notificationTextEl = document.getElementById('notification-text');
    
    // 创建音效元素
    const createSoundElement = (src, volume = 0.5) => {
        const audio = new Audio(src);
        audio.volume = volume;
        return audio;
    };
    
    // 游戏音效
    const sounds = {
        towerBuild: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-construction-hammer-513.mp3', 0.3),
        towerUpgrade: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-unlocking-563.mp3', 0.5),
        towerSell: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-coins-handling-1939.mp3', 0.4),
        enemyHit: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-hit-with-a-hammer-2017.mp3', 0.2),
        enemyDie: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-player-losing-or-failing-2042.mp3', 0.3),
        enemyReachEnd: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3', 0.4),
        waveStart: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-game-start-645.mp3', 0.5),
        coinCollect: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-arcade-game-jump-coin-216.mp3', 0.3),
        gameOver: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-player-losing-or-failing-2042.mp3', 0.6),
        victory: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-achievement-bell-600.mp3', 0.6),
        click: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-select-click-1109.mp3', 0.3),
        tutorial: createSoundElement('https://assets.mixkit.co/sfx/preview/mixkit-interface-hint-notification-911.mp3', 0.4)
    };
    
    // 播放音效
    const playSound = (soundName) => {
        if (gameConfig.soundEnabled && sounds[soundName]) {
            // 克隆音频元素以允许同时播放
            const soundClone = sounds[soundName].cloneNode();
            soundClone.play().catch(e => console.log('Audio play failed:', e));
        }
    };
    
    // 创建加载界面
    const createLoadingScreen = () => {
        const loadingOverlay = document.createElement('div');
        loadingOverlay.className = 'loading-overlay';
        loadingOverlay.innerHTML = `
            <div class="loading-logo"></div>
            <div class="loading-text">载入游戏中...</div>
        `;
        document.body.appendChild(loadingOverlay);
        
        return loadingOverlay;
    };
    
    // 创建音效控制按钮
    const createSoundControl = () => {
        const soundControl = document.createElement('div');
        soundControl.className = 'sound-control';
        soundControl.innerHTML = `<i class="fa fa-volume-up"></i>`;
        soundControl.addEventListener('click', () => {
            gameConfig.soundEnabled = !gameConfig.soundEnabled;
            soundControl.innerHTML = gameConfig.soundEnabled ? 
                `<i class="fa fa-volume-up"></i>` : 
                `<i class="fa fa-volume-off"></i>`;
            playSound('click');
        });
        document.body.appendChild(soundControl);
    };
    
    // 创建暂停按钮和菜单
    const createPauseMenu = () => {
        // 暂停按钮
        const pauseButton = document.createElement('div');
        pauseButton.className = 'sound-control';
        pauseButton.style.bottom = '70px';
        pauseButton.innerHTML = `<i class="fa fa-pause"></i>`;
        document.body.appendChild(pauseButton);
        
        // 暂停菜单
        const pauseMenu = document.createElement('div');
        pauseMenu.className = 'pause-menu';
        pauseMenu.innerHTML = `
            <div class="pause-content">
                <h2>游戏暂停</h2>
                <div class="pause-buttons">
                    <button class="pause-button resume">继续游戏</button>
                    <button class="pause-button restart">重新开始</button>
                    <button class="pause-button tutorial">重新查看教程</button>
                    <button class="pause-button quit">退出游戏</button>
                </div>
            </div>
        `;
        document.body.appendChild(pauseMenu);
        
        // 暂停功能
        let isPaused = false;
        
        const togglePause = () => {
            isPaused = !isPaused;
            
            if (isPaused) {
                clearInterval(gameState.gameLoop);
                pauseMenu.classList.add('show');
                pauseButton.innerHTML = `<i class="fa fa-play"></i>`;
            } else {
                if (gameState.isPlaying) {
                    gameState.gameLoop = setInterval(gameLoop, 30);
                }
                pauseMenu.classList.remove('show');
                pauseButton.innerHTML = `<i class="fa fa-pause"></i>`;
            }
            
            playSound('click');
        };
        
        pauseButton.addEventListener('click', togglePause);
        pauseMenu.querySelector('.resume').addEventListener('click', togglePause);
        pauseMenu.querySelector('.restart').addEventListener('click', () => {
            playSound('click');
            restartGame();
            togglePause();
        });
        pauseMenu.querySelector('.tutorial').addEventListener('click', () => {
            playSound('click');
            startTutorial();
            togglePause();
        });
        pauseMenu.querySelector('.quit').addEventListener('click', () => {
            playSound('click');
            if (confirm('确定要退出游戏吗？当前进度将会丢失。')) {
                showGameResult(false, true);
                togglePause();
            }
        });
    };
    
    // 创建波次通知元素
    const createWaveNotification = () => {
        const waveNotification = document.createElement('div');
        waveNotification.className = 'wave-notification';
        document.body.appendChild(waveNotification);
        return waveNotification;
    };
    
    // 创建游戏结果界面
    const createGameResultScreen = () => {
        const gameResult = document.createElement('div');
        gameResult.className = 'game-result';
        gameResult.innerHTML = `
            <div class="result-icon">🏆</div>
            <h2>游戏结果</h2>
            <p>你成功抵御了敌人的进攻</p>
            <div class="stats">
                <div class="stat-item">
                    <div class="stat-value" id="result-waves">0</div>
                    <div class="stat-label">波次</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="result-enemies">0</div>
                    <div class="stat-label">击杀敌人</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value" id="result-towers">0</div>
                    <div class="stat-label">建造塔数</div>
                </div>
            </div>
            <button id="result-restart" class="game-button-primary font-chinese py-3 px-8 rounded-md text-lg">
                再来一局
            </button>
        `;
        document.body.appendChild(gameResult);
        
        gameResult.querySelector('#result-restart').addEventListener('click', () => {
            playSound('click');
            gameResult.classList.remove('show');
            restartGame();
        });
        
        return gameResult;
    };
    
    // 创建教程提示元素
    const createTutorialTooltip = () => {
        const tooltip = document.createElement('div');
        tooltip.className = 'tutorial-tooltip';
        document.body.appendChild(tooltip);
        return tooltip;
    };
    
    // 初始化游戏元素
    const loadingOverlay = createLoadingScreen();
    const waveNotification = createWaveNotification();
    const gameResultScreen = createGameResultScreen();
    const tutorialTooltip = createTutorialTooltip();
    createSoundControl();
    createPauseMenu();
    
    // 显示通知
    function showNotification(message, type = 'info') {
        // 设置图标和颜色
        let icon = 'fa-info-circle';
        if (type === 'success') icon = 'fa-check-circle text-green-400';
        else if (type === 'warning') icon = 'fa-exclamation-triangle text-yellow-400';
        else if (type === 'error') icon = 'fa-times-circle text-red-400';
        else if (type === 'achievement') {
            icon = 'fa-trophy text-yellow-500 animate-pulse';
            message = `解锁成就: ${message}`;
        }
        
        // 更新内容
        notificationEl.innerHTML = `<i class="fa ${icon}"></i><span id="notification-text">${message}</span>`;
        
        // 显示通知
        notificationEl.classList.add('show');
        
        // 3秒后隐藏，成就通知显示5秒
        const duration = type === 'achievement' ? 5000 : 3000;
        setTimeout(() => {
            notificationEl.classList.remove('show');
        }, duration);
    }
    
    // 显示波次通知
    function showWaveNotification(wave) {
        waveNotification.textContent = `第 ${wave} 波`;
        waveNotification.classList.add('show');
        playSound('waveStart');
        
        setTimeout(() => {
            waveNotification.classList.remove('show');
        }, 2000);
    }
    
    // 显示战斗提示（伤害、奖励等）
    function showBattleHint(x, y, text, type = 'damage') {
        const hint = document.createElement('div');
        hint.className = `battle-hint ${type}`;
        hint.textContent = text;
        hint.style.left = `${x}px`;
        hint.style.top = `${y}px`;
        document.body.appendChild(hint);
        
        setTimeout(() => {
            hint.remove();
        }, 1000);
    }
    
    // 检查成就解锁
    function checkAchievements() {
        // 首杀
        if (gameStats.enemiesKilled >= 1 && !achievements.find(a => a.id === 'first_blood').unlocked) {
            unlockAchievement('first_blood');
        }
        
        // 建塔大师
        if (gameStats.towersBuilt >= 10 && !achievements.find(a => a.id === 'tower_master').unlocked) {
            unlockAchievement('tower_master');
        }
        
        // 十波坚守
        if (gameState.wave >= 10 && !achievements.find(a => a.id === 'wave_10').unlocked) {
            unlockAchievement('wave_10');
        }
        
        // 完美防御
        if (gameState.wave >= 5 && gameStats.livesLost === 0 && 
            !achievements.find(a => a.id === 'no_loss').unlocked) {
            unlockAchievement('no_loss');
        }
        
        // 富可敌国
        if (gameState.money >= 1000 && !achievements.find(a => a.id === 'rich').unlocked) {
            unlockAchievement('rich');
        }
    }
    
    // 解锁成就
    function unlockAchievement(achievementId) {
        const achievement = achievements.find(a => a.id === achievementId);
        if (achievement && !achievement.unlocked) {
            achievement.unlocked = true;
            gameStats.achievements.push(achievement);
            showNotification(achievement.name + " - " + achievement.description, 'achievement');
            playSound('victory');
        }
    }
    
    // 更新统计数据
    function updateStats() {
        enemiesKilledEl.textContent = gameStats.enemiesKilled;
        highestWaveEl.textContent = Math.max(gameStats.highestWave, gameState.wave);
    }
    
    // 显示游戏结果
    function showGameResult(isVictory, isQuit = false) {
        const resultWavesEl = document.getElementById('result-waves');
        const resultEnemiesEl = document.getElementById('result-enemies');
        const resultTowersEl = document.getElementById('result-towers');
        
        resultWavesEl.textContent = isQuit ? gameState.wave : (isVictory ? gameState.wave : gameState.wave - 1);
        resultEnemiesEl.textContent = gameStats.enemiesKilled;
        resultTowersEl.textContent = gameStats.towersBuilt;
        
        const resultIcon = gameResultScreen.querySelector('.result-icon');
        const resultTitle = gameResultScreen.querySelector('h2');
        const resultDesc = gameResultScreen.querySelector('p');
        
        if (isQuit) {
            resultIcon.innerHTML = '🏳️';
            resultTitle.textContent = '游戏退出';
            resultDesc.textContent = '感谢您的游玩，期待下次再战！';
        } else if (isVictory) {
            resultIcon.innerHTML = '🏆';
            resultTitle.textContent = '胜利！';
            resultDesc.textContent = `你成功抵御了${gameState.wave}波敌人的进攻，守护了长城！`;
            playSound('victory');
        } else {
            resultIcon.innerHTML = '💥';
            resultTitle.textContent = '战斗失败';
            resultDesc.textContent = `很遗憾，敌人突破了你的防线，你共抵御了${gameState.wave - 1}波敌人。`;
            playSound('gameOver');
        }
        
        // 显示解锁的成就
        const statsContainer = gameResultScreen.querySelector('.stats');
        const achievementsHTML = gameStats.achievements.map(ach => `
            <div class="stat-item">
                <div class="stat-value">🏆</div>
                <div class="stat-label">${ach.name}</div>
            </div>
        `).join('');
        
        // 如果有成就，添加到统计中
        if (gameStats.achievements.length > 0) {
            statsContainer.innerHTML += achievementsHTML;
        }
        
        gameResultScreen.classList.add('show');
    }
    
    // 游戏教程步骤
    const tutorialSteps = [
        {
            target: '.tower-select[data-tower="crossbow"]',
            position: 'right',
            title: '选择防御塔',
            content: '点击这里选择连弩塔，它能快速攻击敌人。<div class="tutorial-next"><button>下一步</button></div>'
        },
        {
            target: '.tower-place-available',
            position: 'bottom',
            title: '放置防御塔',
            content: '点击这些位置可以放置你选择的防御塔。<div class="tutorial-next"><button>下一步</button></div>'
        },
        {
            target: '#start-button',
            position: 'top',
            title: '开始战斗',
            content: '点击开始按钮，敌人将会从左侧进攻。<div class="tutorial-next"><button>下一步</button></div>'
        },
        {
            target: '.tower-place-available:first-of-type',
            position: 'right',
            title: '战略提示',
            content: '合理布局防御塔，阻止敌人到达右侧的关隘。<div class="tutorial-next"><button>完成</button></div>'
        }
    ];
    
    // 当前教程步骤
    let currentTutorialStep = 0;
    
    // 开始教程
    function startTutorial() {
        currentTutorialStep = 0;
        showTutorialStep(currentTutorialStep);
    }
    
    // 显示教程步骤
    function showTutorialStep(stepIndex) {
        if (stepIndex >= tutorialSteps.length) {
            // 教程结束
            tutorialTooltip.classList.remove('show');
            return;
        }
        
        const step = tutorialSteps[stepIndex];
        const targetEl = document.querySelector(step.target);
        
        if (!targetEl) {
            // 目标元素不存在，跳到下一步
            startTutorialStep(stepIndex + 1);
            return;
        }
        
        // 获取目标元素位置
        const rect = targetEl.getBoundingClientRect();
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
        
        // 设置提示框位置
        tutorialTooltip.className = `tutorial-tooltip ${step.position}`;
        tutorialTooltip.style.top = `${rect.top + rect.height/2 + scrollTop}px`;
        tutorialTooltip.style.left = `${rect.left + rect.width/2 + scrollLeft}px`;
        tutorialTooltip.innerHTML = `<strong>${step.title}</strong><p>${step.content}</p>`;
        
        // 添加下一步事件
        const nextButton = tutorialTooltip.querySelector('button');
        nextButton.addEventListener('click', () => {
            playSound('tutorial');
            currentTutorialStep++;
            showTutorialStep(currentTutorialStep);
        });
        
        // 显示提示框
        tutorialTooltip.classList.add('show');
    }
    
    // 获取Canvas元素并设置上下文
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    
    // 计算FPS
    let lastFrameTime = 0;
    let frameCount = 0;
    let fps = 0;
    
    // 设置Canvas尺寸以匹配显示尺寸
    function resizeCanvas() {
        const container = canvas.parentElement;
        canvas.width = container.clientWidth;
        canvas.height = container.clientHeight;
        // 重绘所有元素
        drawGame();
    }
    
    // 初始化时调整尺寸，并监听窗口大小变化
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);
    
    // 加载背景图片和装饰元素
    const backgroundImg = new Image();
    backgroundImg.src = 'https://picsum.photos/id/1039/1200/900';
    
    const cloudImg = new Image();
    cloudImg.src = 'https://picsum.photos/id/235/200/100';
    
    // 地图装饰元素
    const mapDecorations = [
        {type: 'tree', x: 5, y: 10},
        {type: 'tree', x: 90, y: 15},
        {type: 'tree', x: 5, y: 80},
        {type: 'tree', x: 90, y: 85},
        {type: 'watchtower', x: 20, y: 30},
        {type: 'watchtower', x: 80, y: 70}
    ];
    
    const decorativeElements = [
        {type: 'cloud', x: 10, y: 5, size: 0.8, speed: 0.02},
        {type: 'cloud', x: 70, y: 10, size: 1, speed: 0.015},
        {type: 'cloud', x: 40, y: 8, size: 0.7, speed: 0.025},
        {type: 'bird', x: 20, y: 15, size: 0.3, speed: 0.1},
        {type: 'bird', x: 80, y: 20, size: 0.25, speed: 0.12}
    ];
    
    // 游戏状态变量
    const gameState = {
        money: 500,
        lives: 10,
        wave: 1,
        isPlaying: false,
        selectedTower: null,
        towers: [],
        enemies: [],
        currentEnemyId: 0,
        gameLoop: null,
        attackEffects: [],
        pathPoints: [
            {x: 0, y: 25},   // 起点
            {x: 25, y: 25},
            {x: 50, y: 25},
            {x: 50, y: 40},
            {x: 50, y: 60},
            {x: 25, y: 60},
            {x: 0, y: 60},
            {x: 50, y: 60},
            {x: 75, y: 60},
            {x: 100, y: 60}  // 终点
        ],
        // 粒子效果
        particles: [],
        // 波次计时器
        waveTimer: null,
        // 波次倒计时
        waveCountdown: 0
    };
    
    // DOM元素
    const moneyEl = document.getElementById('money');
    const livesEl = document.getElementById('lives');
    const waveEl = document.getElementById('wave');
    const gameOverlay = document.getElementById('game-overlay');
    const overlayTitle = document.getElementById('overlay-title');
    const overlayMessage = document.getElementById('overlay-message');
    const startButton = document.getElementById('start-button');
    const nextWaveButton = document.getElementById('next-wave');
    const restartButton = document.getElementById('restart');
    const towerSelects = document.querySelectorAll('.tower-select');
    const towerPlaces = document.querySelectorAll('.tower-place-available');
    const towerInfo = document.getElementById('tower-info');
    const towerInfoName = document.getElementById('tower-info-name');
    const towerInfoAttack = document.getElementById('tower-info-attack');
    const towerInfoRange = document.getElementById('tower-info-range');
    const towerInfoSpeed = document.getElementById('tower-info-speed');
    const towerSpecialEffect = document.getElementById('tower-special-effect');
    const towerEffectText = document.getElementById('tower-effect-text');
    const closeTowerInfo = document.getElementById('close-tower-info');
    const upgradeTower = document.getElementById('upgrade-tower');
    const sellTower = document.getElementById('sell-tower');
    
    // 创建塔预览元素
    const towerPreview = document.createElement('div');
    towerPreview.className = 'tower-preview';
    towerPreview.style.display = 'none';
    document.body.appendChild(towerPreview);
    
    // 塔的类型定义
    const towerTypes = {
        crossbow: {
            name: '连弩塔',
            color: '#3B82F6', // 蓝色
            attack: 10,
            range: 15,
            speed: 500,
            cost: 100,
            upgradeCost: 100,
            specialEffect: null,
            killCount: 0, // 用于成就统计
            draw: function(ctx, x, y, size, level) {
                // 塔底座
                ctx.fillStyle = '#1E40AF';
                ctx.fillRect(x - size/4, y - size/4, size/2, size/2);
                
                // 底座纹理
                ctx.fillStyle = '#3B82F6';
                for(let i = 0; i < 3; i++) {
                    for(let j = 0; j < 3; j++) {
                        const brickSize = size/12;
                        ctx.fillRect(
                            x - size/4 + i*brickSize + (j%2 === 0 ? 0 : brickSize/2),
                            y - size/4 + j*brickSize,
                            brickSize*0.8,
                            brickSize*0.8
                        );
                    }
                }
                
                // 塔主体
                ctx.fillStyle = this.color;
                ctx.fillRect(x - size/6, y - size*0.4, size/3, size*0.6);
                
                // 连弩装置
                ctx.fillStyle = '#93C5FD';
                const arrowLength = size * 0.3 + (level - 1) * size * 0.05;
                // 四个方向的弩箭
                for(let i = 0; i < 4; i++) {
                    const angle = i * Math.PI/2;
                    ctx.save();
                    ctx.translate(x, y);
                    ctx.rotate(angle);
                    ctx.fillRect(-size/12, -size/12, arrowLength, size/6);
                    // 箭头
                    ctx.beginPath();
                    ctx.moveTo(arrowLength, 0);
                    ctx.lineTo(arrowLength - size/8, -size/8);
                    ctx.lineTo(arrowLength - size/8, size/8);
                    ctx.closePath();
                    ctx.fillStyle = '#DBEAFE';
                    ctx.fill();
                    ctx.restore();
                }
                
                // 等级装饰
                if(level > 1) {
                    ctx.fillStyle = '#DAA520';
                    ctx.beginPath();
                    ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.fillStyle = '#FFFFFF';
                    ctx.font = `${size/4}px Arial`;
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText(`${level}`, x, y + size/2);
                }
                
                // 升级特效
                if(level > 1) {
                    ctx.strokeStyle = `rgba(218, 165, 32, ${0.3 + Math.sin(Date.now()/300) * 0.1})`;
                    ctx.lineWidth = 2;
                    ctx.beginPath();
                    ctx.arc(x, y, size/3 + (level-1)*size/10, 0, Math.PI * 2);
                    ctx.stroke();
                }
            }
        },
        fire: {
            name: '烽火台',
            color: '#EF4444', // 红色
            attack: 20,
            range: 10,
            speed: 1500,
            cost: 150,
            upgradeCost: 150,
            specialEffect: "范围伤害",
            damageDealt: 0, // 用于成就统计
            draw: function(ctx, x, y, size, level) {
                // 砖石底座
                ctx.fillStyle = '#9CA3AF';
                ctx.fillRect(x - size/3, y - size/4, size*2/3, size/2);
                
                // 绘制砖块纹理
                ctx.strokeStyle = '#6B7280';
                ctx.lineWidth = 1;
                const brickSize = size/10;
                for(let i = 0; i < 3; i++) {
                    for(let j = 0; j < 4; j++) {
                        const offsetX = i % 2 === 0 ? 0 : brickSize/2;
                        ctx.strokeRect(
                            x - size/3 + j*brickSize + offsetX,
                            y - size/4 + i*brickSize,
                            brickSize,
                            brickSize
                        );
                    }
                }
                
                // 烽火台主体
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.ellipse(x, y - size/6, size/4, size/3, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 火焰效果（动态变化）
                const time = Date.now() / 300;
                const flameHeight = size/3 + Math.sin(time) * size/10;
                
                ctx.fillStyle = '#FBBF24';
                ctx.beginPath();
                ctx.moveTo(x, y - size/3);
                ctx.bezierCurveTo(
                    x - size/6 + Math.sin(time + 1) * size/20, y - size/3 - flameHeight,
                    x + size/6 + Math.sin(time) * size/20, y - size/3 - flameHeight,
                    x, y - size/3
                );
                ctx.closePath();
                ctx.fill();
                
                // 火焰外层
                ctx.fillStyle = '#FB923C';
                ctx.beginPath();
                ctx.moveTo(x, y - size/3 + size/10);
                ctx.bezierCurveTo(
                    x - size/5 + Math.sin(time + 2) * size/15, y - size/3 - flameHeight * 0.8,
                    x + size/5 + Math.sin(time + 3) * size/15, y - size/3 - flameHeight * 0.8,
                    x, y - size/3 + size/10
                );
                ctx.closePath();
                ctx.fill();
                
                // 等级标记
                if(level > 1) {
                    ctx.fillStyle = '#DAA520';
                    ctx.beginPath();
                    ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.fillStyle = '#FFFFFF';
                    ctx.font = `${size/4}px Arial`;
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText(`${level}`, x, y + size/2);
                }
            }
        },
        '八卦': {
            name: '八卦阵',
            color: '#F59E0B', // 黄色
            attack: 5,
            range: 20,
            speed: 1000,
            cost: 200,
            upgradeCost: 200,
            slow: 0.5,
            specialEffect: "减速50%",
            draw: function(ctx, x, y, size, level) {
                // 八卦底座
                ctx.fillStyle = '#D97706';
                ctx.beginPath();
                ctx.ellipse(x, y, size/3, size/3, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 旋转动画效果
                const rotation = (Date.now() / 3000) % (Math.PI * 2);
                ctx.save();
                ctx.translate(x, y);
                ctx.rotate(rotation);
                
                // 绘制八卦图案
                ctx.lineWidth = 2;
                ctx.strokeStyle = '#FFFFFF';
                ctx.beginPath();
                ctx.ellipse(0, 0, size/4, size/4, 0, 0, Math.PI * 2);
                ctx.stroke();
                
                // 阴阳线
                ctx.beginPath();
                ctx.moveTo(0, -size/4);
                ctx.lineTo(0, size/4);
                ctx.stroke();
                
                // 阴阳鱼
                ctx.fillStyle = '#FFFFFF';
                ctx.beginPath();
                ctx.ellipse(0, -size/8, size/8, size/8, 0, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.fillStyle = '#D97706';
                ctx.beginPath();
                ctx.ellipse(0, size/8, size/8, size/8, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 小圆点
                ctx.fillStyle = '#D97706';
                ctx.beginPath();
                ctx.ellipse(0, -size/8, size/32, size/32, 0, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.fillStyle = '#FFFFFF';
                ctx.beginPath();
                ctx.ellipse(0, size/8, size/32, size/32, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 八卦符号
                const symbols = [
                    {angle: 0, lines: 3},    // 乾
                    {angle: Math.PI/4, lines: 2}, // 兑
                    {angle: Math.PI/2, lines: 1}, // 离
                    {angle: 3*Math.PI/4, lines: 6}, // 震
                    {angle: Math.PI, lines: 5}, // 巽
                    {angle: 5*Math.PI/4, lines: 4}, // 坎
                    {angle: 3*Math.PI/2, lines: 7}, // 艮
                    {angle: 7*Math.PI/4, lines: 8}  // 坤
                ];
                
                symbols.forEach(sym => {
                    const radius = size/4 * 0.8;
                    const sx = Math.cos(sym.angle) * radius;
                    const sy = Math.sin(sym.angle) * radius;
                    drawTrigram(ctx, sx, sy, size/12, sym.angle);
                });
                
                ctx.restore();
                
                // 等级标记
                if(level > 1) {
                    ctx.fillStyle = '#DAA520';
                    ctx.beginPath();
                    ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.fillStyle = '#FFFFFF';
                    ctx.font = `${size/4}px Arial`;
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText(`${level}`, x, y + size/2);
                }
                
                // 八卦阵光环效果
                ctx.strokeStyle = `rgba(245, 158, 11, ${0.3 + Math.sin(Date.now()/500) * 0.1})`;
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.arc(x, y, size/3 + 2, 0, Math.PI * 2);
                ctx.stroke();
            }
        },
        light: {
            name: '佛光塔',
            color: '#8B5CF6', // 紫色
            attack: 15,
            range: 15,
            speed: 1000,
            cost: 250,
            upgradeCost: 250,
            specialEffect: "穿透伤害",
            draw: function(ctx, x, y, size, level) {
                // 莲花底座
                drawLotus(ctx, x, y, size/3, 8, level);
                
                // 塔主体
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.moveTo(x, y - size/2);
                ctx.lineTo(x - size/6, y - size/6);
                ctx.lineTo(x + size/6, y - size/6);
                ctx.closePath();
                ctx.fill();
                
                // 塔身纹理
                ctx.fillStyle = '#A78BFA';
                for(let i = 0; i < 3; i++) {
                    const segmentHeight = (size/3) / 4;
                    ctx.beginPath();
                    ctx.moveTo(x - size/8 + i*size/40, y - size/2 + segmentHeight*(i+1));
                    ctx.lineTo(x + size/8 - i*size/40, y - size/2 + segmentHeight*(i+1));
                    ctx.strokeStyle = '#C4B5FD';
                    ctx.lineWidth = 1;
                    ctx.stroke();
                }
                
                // 塔顶
                ctx.fillStyle = '#C084FC';
                ctx.beginPath();
                ctx.moveTo(x, y - size/2);
                ctx.lineTo(x - size/8, y - size/3);
                ctx.lineTo(x + size/8, y - size/3);
                ctx.closePath();
                ctx.fill();
                
                // 佛光效果（动态变化）
                const time = Date.now() / 1000;
                const glowSize = size/4 + Math.sin(time) * size/20;
                
                ctx.strokeStyle = `rgba(233, 213, 255, ${0.6 + Math.sin(time * 2) * 0.2})`;
                ctx.lineWidth = 3;
                ctx.beginPath();
                ctx.ellipse(x, y - size/4, glowSize, glowSize * 0.6, 0, 0, Math.PI * 2);
                ctx.stroke();
                
                ctx.strokeStyle = `rgba(216, 180, 254, ${0.4 + Math.sin(time * 2 + 1) * 0.2})`;
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.ellipse(x, y - size/4, glowSize * 1.3, glowSize * 0.8, 0, 0, Math.PI * 2);
                ctx.stroke();
                
                // 等级标记
                if(level > 1) {
                    ctx.fillStyle = '#DAA520';
                    ctx.beginPath();
                    ctx.arc(x, y + size/2, size/8, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.fillStyle = '#FFFFFF';
                    ctx.font = `${size/4}px Arial`;
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    ctx.fillText(`${level}`, x, y + size/2);
                }
            }
        }
    };
    
    // 辅助函数：绘制八卦符号
    function drawTrigram(ctx, x, y, size, angle) {
        ctx.save();
        ctx.translate(x, y);
        ctx.rotate(angle + Math.PI/2);
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 1;
        
        // 绘制三条线
        for(let i = 0; i < 3; i++) {
            const yPos = -size + i * size/2;
            ctx.beginPath();
            ctx.moveTo(-size/2, yPos);
            ctx.lineTo(size/2, yPos);
            ctx.stroke();
        }
        
        ctx.restore();
    }
    
    // 辅助函数：绘制莲花底座
    function drawLotus(ctx, x, y, size, petals, level) {
        const time = Date.now() / 2000;
        for(let i = 0; i < petals + (level-1)*2; i++) {
            const angle = (i / (petals + (level-1)*2)) * Math.PI * 2 + time;
            const petalX = x + Math.cos(angle) * size * 0.7;
            const petalY = y + Math.sin(angle) * size * 0.7;
            const petalSize = size/4 + Math.sin(angle * 2 + time) * size/20;
            
            ctx.save();
            ctx.translate(petalX, petalY);
            ctx.rotate(angle);
            
            ctx.beginPath();
            ctx.ellipse(0, 0, petalSize, petalSize/2, 0, 0, Math.PI * 2);
            ctx.fillStyle = `rgba(237, 233, 254, ${0.7 + Math.sin(angle * 3 + time) * 0.2})`;
            ctx.fill();
            
            ctx.restore();
        }
    }
    
    // 敌人类型定义
    const enemyTypes = {
        soldier: {
            name: '匈奴骑兵',
            color: '#B45309', // 棕色
            health: 50,
            speed: 1,
            reward: 50,
            draw: function(ctx, x, y, size, healthPercent) {
                // 骑兵身体
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.ellipse(x, y, size/2, size/3, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 身体纹理
                ctx.strokeStyle = '#92400E';
                ctx.lineWidth = 1;
                ctx.beginPath();
                ctx.moveTo(x - size/2, y);
                ctx.lineTo(x + size/2, y);
                ctx.stroke();
                
                // 骑兵头部
                ctx.fillStyle = '#92400E';
                ctx.beginPath();
                ctx.ellipse(x, y - size/3, size/4, size/4, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 眼睛
                ctx.fillStyle = '#FFFFFF';
                ctx.beginPath();
                ctx.ellipse(x + size/12, y - size/3, size/20, size/20, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 骑兵武器
                ctx.fillStyle = '#4B5563';
                ctx.beginPath();
                ctx.rect(x + size/4, y - size/4, size/2, size/8);
                ctx.fill();
                
                // 武器细节
                ctx.fillStyle = '#6B7280';
                ctx.beginPath();
                ctx.rect(x + size/4 + size/3, y - size/4, size/6, size/8);
                ctx.fill();
                
                // 绘制血量
                drawHealthBar(ctx, x, y - size/2, size, healthPercent);
                
                // 呼吸效果
                const scale = 1 + Math.sin(Date.now()/500) * 0.03;
                ctx.save();
                ctx.translate(x, y);
                ctx.scale(scale, 1);
                ctx.restore();
            }
        },
        taotie: {
            name: '饕餮',
            color: '#059669', // 绿色
            health: 150,
            speed: 0.5,
            reward: 150,
            draw: function(ctx, x, y, size, healthPercent) {
                // 饕餮身体
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.ellipse(x, y, size/2, size/2, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 身体纹理
                ctx.fillStyle = '#065F46';
                for(let i = 0; i < 5; i++) {
                    const angle = (i / 5) * Math.PI * 2;
                    const offset = size/5;
                    ctx.beginPath();
                    ctx.arc(
                        x + Math.cos(angle) * offset,
                        y + Math.sin(angle) * offset,
                        size/15, 0, Math.PI * 2
                    );
                    ctx.fill();
                }
                
                // 饕餮头部
                ctx.fillStyle = '#065F46';
                ctx.beginPath();
                ctx.ellipse(x, y, size/3, size/3, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 饕餮眼睛
                ctx.fillStyle = '#FFFFFF';
                ctx.beginPath();
                ctx.ellipse(x - size/8, y - size/10, size/12, size/12, 0, 0, Math.PI * 2);
                ctx.ellipse(x + size/8, y - size/10, size/12, size/12, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 眼球
                ctx.fillStyle = '#000000';
                ctx.beginPath();
                ctx.ellipse(x - size/8 + size/40, y - size/10, size/30, size/30, 0, 0, Math.PI * 2);
                ctx.ellipse(x + size/8 + size/40, y - size/10, size/30, size/30, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 饕餮嘴巴
                ctx.fillStyle = '#033F30';
                ctx.beginPath();
                ctx.arc(x, y + size/10, size/10, 0, Math.PI, false);
                ctx.fill();
                
                // 牙齿
                ctx.fillStyle = '#FFFFFF';
                for(let i = 0; i < 5; i++) {
                    const angle = Math.PI/6 + (i * Math.PI/6);
                    const toothX = x + Math.cos(angle) * size/10;
                    const toothY = y + Math.sin(angle) * size/10;
                    ctx.beginPath();
                    ctx.moveTo(toothX, toothY);
                    ctx.lineTo(toothX + Math.cos(angle) * size/20, toothY + Math.sin(angle) * size/20);
                    ctx.lineTo(toothX + Math.cos(angle + 0.2) * size/20, toothY + Math.sin(angle + 0.2) * size/20);
                    ctx.closePath();
                    ctx.fill();
                }
                
                // 绘制血量
                drawHealthBar(ctx, x, y - size/2, size, healthPercent);
                
                // 缓慢的脉动效果
                const scale = 1 + Math.sin(Date.now()/1000) * 0.02;
                ctx.save();
                ctx.translate(x, y);
                ctx.scale(scale, scale);
                ctx.restore();
            }
        },
        bifang: {
            name: '毕方',
            color: '#DC2626', // 红色
            health: 80,
            speed: 0.8,
            reward: 100,
            resistances: ['fire'],
            draw: function(ctx, x, y, size, healthPercent) {
                // 毕方身体
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.ellipse(x, y, size/3, size/4, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 身体纹理
                ctx.fillStyle = '#B91C1C';
                for(let i = 0; i < 3; i++) {
                    const yOffset = -size/8 + (i * size/8);
                    ctx.beginPath();
                    ctx.ellipse(x, y + yOffset, size/6 - i*size/30, size/16, 0, 0, Math.PI * 2);
                    ctx.fill();
                }
                
                // 毕方翅膀（动态效果）
                const time = Date.now() / 500;
                const wingAngle = Math.sin(time) * 0.3;
                
                ctx.fillStyle = '#B91C1C';
                ctx.save();
                ctx.translate(x - size/3, y);
                ctx.rotate(wingAngle);
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.bezierCurveTo(
                    -size/2, -size/3,
                    -size/4, -size/4,
                    0, size/4
                );
                ctx.closePath();
                ctx.fill();
                ctx.restore();
                
                // 毕方头部
                ctx.fillStyle = '#991B1B';
                ctx.beginPath();
                ctx.ellipse(x + size/4, y, size/6, size/6, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 眼睛
                ctx.fillStyle = '#FFFFFF';
                ctx.beginPath();
                ctx.ellipse(x + size/4 + size/20, y - size/20, size/30, size/30, 0, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.fillStyle = '#000000';
                ctx.beginPath();
                ctx.ellipse(x + size/4 + size/18, y - size/20, size/50, size/50, 0, 0, Math.PI * 2);
                ctx.fill();
                
                // 毕方火焰（动态效果）
                const flameTime = Date.now() / 300;
                ctx.fillStyle = '#FBBF24';
                ctx.beginPath();
                ctx.moveTo(x + size/4, y);
                ctx.bezierCurveTo(
                    x + size/2 + Math.sin(flameTime) * size/20, y - size/6,
                    x + size/2 + Math.sin(flameTime + 1) * size/20, y + size/6,
                    x + size/4, y
                );
                ctx.closePath();
                ctx.fill();
                
                // 火焰外层
                ctx.fillStyle = '#FB923C';
                ctx.beginPath();
                ctx.moveTo(x + size/4 + size/20, y + size/20);
                ctx.bezierCurveTo(
                    x + size/2 + size/10 + Math.sin(flameTime + 2) * size/15, y - size/6,
                    x + size/2 + size/10 + Math.sin(flameTime + 3) * size/15, y + size/6,
                    x + size/4 + size/20, y + size/20
                );
                ctx.closePath();
                ctx.fill();
                
                // 绘制血量
                drawHealthBar(ctx, x, y - size/2, size, healthPercent);
            }
        }
    };
    
    // 绘制血条辅助函数
    function drawHealthBar(ctx, x, y, size, percent) {
        // 血条背景
        ctx.fillStyle = '#9CA3AF';
        ctx.fillRect(x - size/2, y, size, size/8);
        
        // 血条填充
        let fillColor = '#10B981'; // 绿色
        if(percent < 30) fillColor = '#EF4444'; // 红色
        else if(percent < 60) fillColor = '#F59E0B'; // 黄色
        
        ctx.fillStyle = fillColor;
        ctx.fillRect(x - size/2, y, size * (percent/100), size/8);
        
        // 血条边框
        ctx.strokeStyle = '#4B5563';
        ctx.lineWidth = 1;
        ctx.strokeRect(x - size/2, y, size, size/8);
    }
    
    // 创建粒子效果
    function createParticles(x, y, count, color, sizeRange = [2, 5]) {
        for(let i = 0; i < count; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = 1 + Math.random() * 2;
            const size = sizeRange[0] + Math.random() * (sizeRange[1] - sizeRange[0]);
            
            gameState.particles.push({
                x: x,
                y: y,
                size: size,
                speed: speed,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed,
                color: color,
                alpha: 1,
                life: 30 + Math.random() * 20
            });
        }
    }
    
    // 更新粒子效果
    function updateParticles() {
        for(let i = gameState.particles.length - 1; i >= 0; i--) {
            const p = gameState.particles[i];
            
            // 更新位置
            p.x += p.vx;
            p.y += p.vy;
            
            // 减速
            p.vx *= 0.95;
            p.vy *= 0.95;
            
            // 减少生命值
            p.life--;
            p.alpha = p.life / 50;
            
            // 移除死亡粒子
            if(p.life <= 0) {
                gameState.particles.splice(i, 1);
            }
        }
    }
    
    // 绘制粒子效果
    function drawParticles() {
        gameState.particles.forEach(p => {
            ctx.save();
            ctx.globalAlpha = p.alpha;
            ctx.fillStyle = p.color;
            ctx.beginPath();
            ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        });
    }
    
    // 更新装饰元素位置
    function updateDecorativeElements() {
        decorativeElements.forEach(el => {
            el.x += el.speed;
            if(el.x > 110) {
                el.x = -10;
            }
        });
    }
    
    // 绘制装饰元素
    function drawDecorativeElements() {
        decorativeElements.forEach(el => {
            const pos = getPixelPosition({x: el.x, y: el.y});
            
            if(el.type === 'cloud' && cloudImg.complete) {
                ctx.save();
                ctx.globalAlpha = 0.6;
                ctx.drawImage(
                    cloudImg, 
                    pos.x - (cloudImg.width * el.size / 2), 
                    pos.y - (cloudImg.height * el.size / 2),
                    cloudImg.width * el.size,
                    cloudImg.height * el.size
                );
                ctx.restore();
            } else if(el.type === 'bird') {
                // 绘制简单的鸟形
                ctx.save();
                ctx.translate(pos.x, pos.y);
                ctx.scale(el.size, el.size);
                
                ctx.fillStyle = '#2C3E50';
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(15, -5);
                ctx.lineTo(30, 0);
                ctx.lineTo(15, 5);
                ctx.closePath();
                ctx.fill();
                
                ctx.restore();
            }
        });
    }
    
    // 绘制地图装饰
    function drawMapDecorations() {
        mapDecorations.forEach(decor => {
            const pos = getPixelPosition({x: decor.x, y: decor.y});
            
            const decorEl = document.createElement('div');
            decorEl.className = `map-decoration ${decor.type}`;
            decorEl.style.left = `${pos.x}px`;
            decorEl.style.top = `${pos.y}px`;
            
            // 检查是否已存在该装饰，避免重复添加
            const existing = document.querySelector(`.map-decoration.${decor.type}[style*="left: ${pos.x}px"][style*="top: ${pos.y}px"]`);
            if (!existing) {
                canvas.parentElement.appendChild(decorEl);
            }
        });
    }
    
    // 更新游戏状态显示
    function updateGameStatus() {
        moneyEl.textContent = gameState.money;
        livesEl.textContent = gameState.lives;
        waveEl.textContent = `第${gameState.wave}波`;
        
        // 更新波次倒计时
        if (gameState.waveCountdown > 0) {
            nextWaveButton.textContent = `下一波 (${gameState.waveCountdown}s)`;
        } else {
            nextWaveButton.textContent = '下一波';
        }
    }
    
    // 绘制游戏场景
    function drawGame(timestamp) {
        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 计算FPS
        if (gameConfig.showFPS && timestamp) {
            if (lastFrameTime) {
                const delta = timestamp - lastFrameTime;
                fps = Math.round(1000 / delta);
            }
            lastFrameTime = timestamp;
            frameCount++;
        }
        
        // 绘制背景图（降低透明度）
        if(backgroundImg.complete) {
            ctx.globalAlpha = 0.5; // 降低背景透明度，防止影响游戏元素观感
            ctx.drawImage(backgroundImg, 0, 0, canvas.width, canvas.height);
            ctx.globalAlpha = 1; // 恢复透明度
        }
        
        // 绘制装饰性元素（云、鸟等）
        drawDecorativeElements();
        
        // 绘制路径
        drawPath();
        
        // 绘制起点和终点标记
        drawStartEndPoints();
        
        // 绘制粒子效果
        drawParticles();
        
        // 绘制攻击效果
        drawAttackEffects();
        
        // 绘制敌人
        drawEnemies();
        
        // 绘制防御塔
        drawTowers();
        
        // 绘制塔的攻击范围（当选中时）
        drawTowerRanges();
        
        // 显示FPS
        if (gameConfig.showFPS) {
            ctx.fillStyle = 'black';
            ctx.font = '12px Arial';
            ctx.fillText(`FPS: ${fps}`, 10, 20);
        }
    }
    
    // 绘制敌人路径
    function drawPath() {
        ctx.beginPath();
        ctx.lineWidth = canvas.height * 0.05; // 路径宽度
        ctx.strokeStyle = 'rgba(139, 69, 19, 0.2)'; // 木色半透明
        
        // 添加路径纹理
        const gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
        gradient.addColorStop(0, 'rgba(139, 69, 19, 0.1)');
        gradient.addColorStop(0.5, 'rgba(139, 69, 19, 0.3)');
        gradient.addColorStop(1, 'rgba(139, 69, 19, 0.1)');
        ctx.strokeStyle = gradient;
        
        // 将百分比坐标转换为实际像素坐标
        const firstPoint = getPixelPosition(gameState.pathPoints[0]);
        ctx.moveTo(firstPoint.x, firstPoint.y);
        
        // 绘制路径线段
        for(let i = 1; i < gameState.pathPoints.length; i++) {
            const point = getPixelPosition(gameState.pathPoints[i]);
            ctx.lineTo(point.x, point.y);
        }
        
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        ctx.stroke();
        
        // 路径边缘
        ctx.lineWidth = canvas.height * 0.005;
        ctx.strokeStyle = 'rgba(139, 69, 19, 0.5)';
        ctx.stroke();
        
        // 路径纹理 - 砖块效果
        ctx.lineWidth = 1;
        ctx.strokeStyle = 'rgba(139, 69, 19, 0.3)';
        
        const segmentLength = canvas.width * 0.05; // 每段长度
        let currentLength = 0;
        
        for(let i = 0; i < gameState.pathPoints.length - 1; i++) {
            const start = getPixelPosition(gameState.pathPoints[i]);
            const end = getPixelPosition(gameState.pathPoints[i+1]);
            const dx = end.x - start.x;
            const dy = end.y - start.y;
            const length = Math.sqrt(dx * dx + dy * dy);
            const dirX = dx / length;
            const dirY = dy / length;
            
            // 绘制垂直于路径的短线段作为纹理
            for(let j = 0; j < length; j += segmentLength) {
                const posX = start.x + dirX * j;
                const posY = start.y + dirY * j;
                
                // 垂直方向
                const perpX = -dirY;
                const perpY = dirX;
                
                // 路径宽度的一半
                const halfWidth = canvas.height * 0.025;
                
                ctx.beginPath();
                ctx.moveTo(posX + perpX * halfWidth, posY + perpY * halfWidth);
                ctx.lineTo(posX - perpX * halfWidth, posY - perpY * halfWidth);
                ctx.stroke();
            }
        }
    }
    
    // 绘制起点和终点标记
    function drawStartEndPoints() {
        // 起点 - 敌营
        const startPoint = getPixelPosition(gameState.pathPoints[0]);
        
        // 绘制旗帜
        ctx.fillStyle = '#CD5C5C';
        ctx.fillRect(startPoint.x - 5, startPoint.y - 30, 10, 30);
        
        ctx.fillStyle = '#2C3E50';
        ctx.beginPath();
        ctx.moveTo(startPoint.x + 5, startPoint.y - 30);
        ctx.lineTo(startPoint.x + 20, startPoint.y - 40);
        ctx.lineTo(startPoint.x + 5, startPoint.y - 20);
        ctx.closePath();
        ctx.fill();
        
        // 文字
        ctx.fillStyle = '#2C3E50';
        ctx.font = `${canvas.height * 0.025}px 'Ma Shan Zheng', serif`;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('敌营', startPoint.x - canvas.width * 0.03, startPoint.y);
        
        // 终点 - 关隘
        const endPoint = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
        
        // 绘制城门
        ctx.fillStyle = '#8B4513';
        ctx.fillRect(endPoint.x - 20, endPoint.y - 20, 40, 40);
        
        ctx.fillStyle = '#D2B48C';
        ctx.fillRect(endPoint.x - 10, endPoint.y - 10, 20, 20);
        
        // 文字
        ctx.fillStyle = '#2C3E50';
        ctx.fillText('关隘', endPoint.x + canvas.width * 0.03, endPoint.y);
    }
    
    // 绘制敌人
    function drawEnemies() {
        const enemySize = canvas.height * 0.03; // 敌人大小
        
        gameState.enemies.forEach(enemy => {
            // 获取当前位置
            let currentPos;
            if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                const currentPoint = gameState.pathPoints[enemy.pathIndex];
                const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                
                // 计算当前位置
                const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                currentPos = getPixelPosition({x, y});
            } else {
                currentPos = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
            }
            
            // 计算生命值百分比
            const healthPercent = (enemy.health / enemy.maxHealth) * 100;
            
            // 绘制敌人
            enemyTypes[enemy.type].draw(ctx, currentPos.x, currentPos.y, enemySize, healthPercent);
        });
    }
    
    // 绘制防御塔
    function drawTowers() {
        const towerSize = canvas.height * 0.04; // 塔的大小
        
        gameState.towers.forEach(tower => {
            const pos = getPixelPosition({x: tower.x, y: tower.y});
            towerTypes[tower.type].draw(ctx, pos.x, pos.y, towerSize, tower.level);
        });
    }
    
    // 绘制塔的攻击范围（当选中时）
    function drawTowerRanges() {
        const selectedTowerId = towerInfo.getAttribute('data-tower-id');
        if (!selectedTowerId || towerInfo.style.display === 'none') return;
        
        const tower = gameState.towers.find(t => t.id === selectedTowerId);
        if (!tower) return;
        
        const pos = getPixelPosition({x: tower.x, y: tower.y});
        const rangePixel = (tower.range / 100) * canvas.width; // 将百分比范围转换为像素
        
        // 创建渐变光环
        const gradient = ctx.createRadialGradient(
            pos.x, pos.y, rangePixel * 0.8,
            pos.x, pos.y, rangePixel
        );
        gradient.addColorStop(0, 'rgba(218, 165, 32, 0.1)');
        gradient.addColorStop(1, 'rgba(218, 165, 32, 0)');
        
        // 绘制半透明范围圈
        ctx.beginPath();
        ctx.arc(pos.x, pos.y, rangePixel, 0, Math.PI * 2);
        ctx.fillStyle = gradient;
        ctx.fill();
        
        // 范围边界
        ctx.strokeStyle = 'rgba(218, 165, 32, 0.3)';
        ctx.lineWidth = 2;
        ctx.setLineDash([5, 5]);
        ctx.beginPath();
        ctx.arc(pos.x, pos.y, rangePixel, 0, Math.PI * 2);
        ctx.stroke();
        ctx.setLineDash([]); // 重置虚线
    }
    
    // 绘制攻击效果
    function drawAttackEffects() {
        const effectSize = canvas.height * 0.02;
        
        // 清除已结束的效果
        gameState.attackEffects = gameState.attackEffects.filter(effect => {
            return Date.now() - effect.createdAt < 300; // 效果持续300ms
        });
        
        // 绘制剩余效果
        gameState.attackEffects.forEach(effect => {
            const pos = getPixelPosition(effect.position);
            const age = Date.now() - effect.createdAt;
            const progress = age / 300;
            
            // 根据塔类型设置不同的攻击效果颜色
            let color = 'rgba(218, 165, 32, 1)'; // 默认金色
            if (effect.towerType === 'fire') color = 'rgba(239, 68, 68, 1)'; // 红色
            else if (effect.towerType === 'crossbow') color = 'rgba(59, 130, 246, 1)'; // 蓝色
            else if (effect.towerType === 'light') color = 'rgba(139, 92, 246, 1)'; // 紫色
            
            ctx.beginPath();
            ctx.arc(pos.x, pos.y, effectSize * (1 + progress * 2), 0, Math.PI * 2);
            ctx.fillStyle = `${color}${Math.floor((1 - progress) * 100) / 100}`;
            ctx.fill();
        });
    }
    
    // 坐标转换：百分比 -> 像素
    function getPixelPosition(percentPos) {
        return {
            x: (percentPos.x / 100) * canvas.width,
            y: (percentPos.y / 100) * canvas.height
        };
    }
    
    // 坐标转换：像素 -> 百分比
    function getPercentPosition(pixelPos) {
        return {
            x: (pixelPos.x / canvas.width) * 100,
            y: (pixelPos.y / canvas.height) * 100
        };
    }
    
    // 显示塔预览
    function showTowerPreview(x, y, towerType) {
        if (!towerType) {
            towerPreview.style.display = 'none';
            return;
        }
        
        const towerInfo = towerTypes[towerType];
        towerPreview.innerHTML = `<i class="fa ${
            towerType === 'crossbow' ? 'fa-crosshairs' : 
            towerType === 'fire' ? 'fa-fire' : 
            towerType === '八卦' ? 'fa-th' : 'fa-star'
        } text-2xl"></i>`;
        towerPreview.className = `tower-preview ${
            towerType === 'crossbow' ? 'text-tower-crossbow' : 
            towerType === 'fire' ? 'text-tower-fire' : 
            towerType === '八卦' ? 'text-tower-bagua' : 'text-tower-light'
        }`;
        
        towerPreview.style.left = `${x}px`;
        towerPreview.style.top = `${y}px`;
        towerPreview.style.display = 'block';
    }
    
    // 选择防御塔
    towerSelects.forEach(select => {
        select.addEventListener('click', function() {
            // 移除其他选中状态
            towerSelects.forEach(s => s.classList.remove('border-primary', 'bg-primary/10'));
            // 添加当前选中状态
            this.classList.add('border-primary', 'bg-primary/10');
            
            const towerType = this.getAttribute('data-tower');
            gameState.selectedTower = towerType;
            
            showNotification(`已选择${towerTypes[towerType].name}，点击可放置位置进行建造`, 'info');
            playSound('click');
        });
    });
    
    // 鼠标移动时显示塔预览
    document.addEventListener('mousemove', function(e) {
        if (gameState.selectedTower && gameState.isPlaying) {
            showTowerPreview(e.clientX + 10, e.clientY - 10, gameState.selectedTower);
        } else {
            towerPreview.style.display = 'none';
        }
    });
    
    // 放置防御塔
    towerPlaces.forEach(place => {
        place.addEventListener('click', function() {
            if (!gameState.selectedTower || !gameState.isPlaying) return;
            
            const towerType = towerTypes[gameState.selectedTower];
            const cost = towerType.cost;
            
            // 检查是否有足够的钱
            if (gameState.money < cost) {
                showNotification('铜钱不足，无法建造此防御塔', 'error');
                return;
            }
            
            // 检查是否已经放置了塔
            if (this.classList.contains('tower-place-unavailable')) {
                return;
            }
            
            // 扣除金钱
            gameState.money -= cost;
            updateGameStatus();
            
            // 标记为不可用
            this.classList.remove('tower-place-available');
            this.classList.add('tower-place-unavailable');
            
            // 创建塔
            const x = parseInt(this.getAttribute('data-x'));
            const y = parseInt(this.getAttribute('data-y'));
            const towerId = `tower-${Date.now()}`;
            
            const tower = {
                id: towerId,
                type: gameState.selectedTower,
                x: x,
                y: y,
                level: 1,
                attack: towerType.attack,
                range: towerType.range,
                speed: towerType.speed,
                lastAttack: 0
            };
            
            gameState.towers.push(tower);
            gameStats.towersBuilt++;
            
            // 创建放置粒子效果
            const pos = getPixelPosition({x, y});
            createParticles(
                pos.x, pos.y, 15, 
                towerType.color.replace('rgb', 'rgba').replace(')', ', 0.8)'),
                [3, 6]
            );
            
            showNotification(`成功建造${towerType.name}`, 'success');
            playSound('towerBuild');
            
            // 检查成就
            checkAchievements();
            
            // 重绘游戏
            drawGame();
        });
    });
    
    // 显示塔的信息
    function showTowerInfo(tower) {
        const towerType = towerTypes[tower.type];
        
        towerInfoName.textContent = `${towerType.name} Lv.${tower.level}`;
        towerInfoAttack.textContent = tower.attack;
        towerInfoRange.textContent = `${tower.range}%`;
        towerInfoSpeed.textContent = towerType.speed < 800 ? '快' : towerType.speed < 1300 ? '中' : '慢';
        
        // 显示特殊效果
        if (towerType.specialEffect) {
            towerSpecialEffect.style.display = 'flex';
            towerEffectText.textContent = towerType.specialEffect;
        } else {
            towerSpecialEffect.style.display = 'none';
        }
        
        // 存储当前选中的塔ID
        towerInfo.setAttribute('data-tower-id', tower.id);
        
        // 更新升级按钮
        upgradeTower.innerHTML = `<i class="fa fa-level-up mr-1"></i> 升级 (${towerType.upgradeCost * tower.level})`;
        
        // 显示信息面板
        towerInfo.style.display = 'block';
        setTimeout(() => {
            towerInfo.classList.remove('scale-95', 'opacity-0', 'pointer-events-none');
        }, 10);
        
        // 重绘以显示攻击范围
        drawGame();
    }
    
    // 关闭塔信息
    closeTowerInfo.addEventListener('click', function() {
        towerInfo.classList.add('scale-95', 'opacity-0', 'pointer-events-none');
        setTimeout(() => {
            towerInfo.style.display = 'none';
        }, 300);
        drawGame(); // 重绘以移除攻击范围显示
        playSound('click');
    });
    
    // 升级塔
    upgradeTower.addEventListener('click', function() {
        const towerId = towerInfo.getAttribute('data-tower-id');
        const tower = gameState.towers.find(t => t.id === towerId);
        
        if (!tower) return;
        
        const towerType = towerTypes[tower.type];
        const upgradeCost = towerType.upgradeCost * tower.level;
        
        if (gameState.money < upgradeCost) {
            showNotification('铜钱不足，无法升级此防御塔', 'error');
            return;
        }
        
        // 扣除金钱
        gameState.money -= upgradeCost;
        updateGameStatus();
        
        // 升级塔
        tower.level += 1;
        tower.attack = Math.round(tower.attack * 1.5);
        tower.range = Math.round(tower.range * 1.2);
        gameStats.towersUpgraded++;
        
        // 创建升级粒子效果
        const pos = getPixelPosition({x: tower.x, y: tower.y});
        createParticles(
            pos.x, pos.y, 20, 
            '#DAA520',
            [2, 5]
        );
        
        // 更新显示
        showTowerInfo(tower);
        showNotification(`${towerType.name} 已升级到 Lv.${tower.level}`, 'success');
        playSound('towerUpgrade');
        
        // 重绘游戏
        drawGame();
    });
    
    // 出售塔
    sellTower.addEventListener('click', function() {
        const towerId = towerInfo.getAttribute('data-tower-id');
        const towerIndex = gameState.towers.findIndex(t => t.id === towerId);
        
        if (towerIndex === -1) return;
        
        const tower = gameState.towers[towerIndex];
        const towerType = towerTypes[tower.type];
        
        // 计算出售价格
        const sellPrice = Math.round((towerType.cost * (tower.level * 0.5)) * 0.7);
        
        // 增加金钱
        gameState.money += sellPrice;
        updateGameStatus();
        
        // 创建出售粒子效果
        const pos = getPixelPosition({x: tower.x, y: tower.y});
        createParticles(
            pos.x, pos.y, 15, 
            '#9CA3AF',
            [2, 4]
        );
        
        // 恢复放置位置可用
        const place = document.querySelector(`.tower-place[data-x="${tower.x}"][data-y="${tower.y}"]`);
        if (place) {
            place.classList.remove('tower-place-unavailable');
            place.classList.add('tower-place-available');
        }
        
        // 从数组中移除
        gameState.towers.splice(towerIndex, 1);
        
        showNotification(`已出售${towerType.name}，获得 ${sellPrice} 铜钱`, 'info');
        playSound('towerSell');
        
        // 关闭信息面板
        towerInfo.classList.add('scale-95', 'opacity-0', 'pointer-events-none');
        setTimeout(() => {
            towerInfo.style.display = 'none';
        }, 300);
        
        // 重绘游戏
        drawGame();
    });
    
    // 创建敌人
    function createEnemy(type, wave) {
        const enemyType = enemyTypes[type];
        const enemyId = `enemy-${gameState.currentEnemyId++}`;
        
        // 根据波次和难度增强敌人
        const difficultyMultiplier = gameConfig.difficulty === 'easy' ? 0.8 : 
                                    gameConfig.difficulty === 'hard' ? 1.3 : 1;
        const multiplier = difficultyMultiplier * (1 + (wave - 1) * 0.2);
        const health = Math.round(enemyType.health * multiplier);
        const reward = Math.round(enemyType.reward * multiplier);
        const speed = enemyType.speed * (1 + (wave - 1) * 0.05) * (gameConfig.difficulty === 'easy' ? 0.9 : 
                                                                   gameConfig.difficulty === 'hard' ? 1.2 : 1);
        
        const enemy = {
            id: enemyId,
            type: type,
            health: health,
            maxHealth: health,
            speed: speed,
            reward: reward,
            resistances: enemyType.resistances || [],
            pathIndex: 0,
            progress: 0,
            slowFactor: 1
        };
        
        gameState.enemies.push(enemy);
        
        return enemy;
    }
    
    // 生成一波敌人
    function spawnWave(wave) {
        // 清除波次倒计时
        if (gameState.waveTimer) {
            clearInterval(gameState.waveTimer);
            gameState.waveTimer = null;
            gameState.waveCountdown = 0;
            updateGameStatus();
        }
        
        nextWaveButton.disabled = true;
        const baseEnemyCount = 5;
        const enemyCount = baseEnemyCount + Math.floor(wave * 1.5);
        let enemiesSpawned = 0;
        
        showWaveNotification(wave);
        
        // 根据波次调整敌人类型比例
        let enemyTypeDistribution = {
            soldier: 0.6,
            taotie: 0.3,
            bifang: 0.1
        };
        
        // 随着波次增加，更强的敌人比例增加
        if (wave >= 5) {
            enemyTypeDistribution = {
                soldier: 0.5,
                taotie: 0.35,
                bifang: 0.15
            };
        }
        
        if (wave >= 10) {
            enemyTypeDistribution = {
                soldier: 0.4,
                taotie: 0.4,
                bifang: 0.2
            };
        }
        
        if (wave >= 15) {
            enemyTypeDistribution = {
                soldier: 0.3,
                taotie: 0.45,
                bifang: 0.25
            };
        }
        
        const spawnInterval = setInterval(() => {
            if (!gameState.isPlaying) {
                clearInterval(spawnInterval);
                return;
            }
            
            if (enemiesSpawned >= enemyCount) {
                clearInterval(spawnInterval);
                return;
            }
            
            // 根据分布随机选择敌人类型
            const rand = Math.random();
            let enemyType;
            
            if (rand < enemyTypeDistribution.soldier) {
                enemyType = 'soldier';
            } else if (rand < enemyTypeDistribution.soldier + enemyTypeDistribution.taotie) {
                enemyType = 'taotie';
            } else {
                enemyType = 'bifang';
            }
            
            createEnemy(enemyType, wave);
            enemiesSpawned++;
        }, 1500 - Math.min(wave * 50, 1000)); // 随着波次增加，生成间隔缩短，最低500ms
    }
    
    // 更新敌人位置
    function updateEnemies() {
        gameState.enemies.forEach(enemy => {
            if (enemy.pathIndex >= gameState.pathPoints.length - 1) {
                // 到达终点，扣除生命值
                gameState.lives--;
                gameStats.livesLost++;
                updateGameStatus();
                
                // 创建生命值减少效果
                const endPoint = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
                createParticles(
                    endPoint.x, endPoint.y, 10, 
                    '#EF4444',
                    [3, 6]
                );
                
                // 显示伤害提示
                const pixelPos = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
                showBattleHint(pixelPos.x, pixelPos.y - 20, "-1", 'damage');
                
                if (gameState.lives <= 0) {
                    showNotification('生命值耗尽！', 'error');
                } else {
                    showNotification(`敌人突破防线，剩余生命值: ${gameState.lives}`, 'warning');
                }
                
                playSound('enemyReachEnd');
                
                // 移除敌人
                removeEnemy(enemy.id);
                
                // 检查游戏是否结束
                if (gameState.lives <= 0) {
                    endGame(false);
                }
                return;
            }
            
            // 移动到下一个路径点
            const currentPoint = gameState.pathPoints[enemy.pathIndex];
            const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
            
            // 计算距离
            const dx = nextPoint.x - currentPoint.x;
            const dy = nextPoint.y - currentPoint.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            // 更新进度（考虑减速效果）
            enemy.progress += (enemy.speed / distance) * enemy.slowFactor;
            
            if (enemy.progress >= 1) {
                // 到达下一个点
                enemy.pathIndex++;
                enemy.progress = 0;
            }
            
            // 重置减速效果（每帧重置，由八卦阵持续施加）
            if (enemy.slowFactor !== 1) {
                enemy.slowFactor = Math.min(1, enemy.slowFactor + 0.02);
            }
        });
    }
    
    // 移除敌人
    function removeEnemy(enemyId) {
        // 从数组中移除
        const enemyIndex = gameState.enemies.findIndex(enemy => enemy.id === enemyId);
        if (enemyIndex !== -1) {
            const enemy = gameState.enemies[enemyIndex];
            
            // 如果是被击杀的，增加统计
            if (enemy.health <= 0) {
                gameStats.enemiesKilled++;
                gameStats.coinsEarned += enemy.reward;
                
                // 显示奖励提示
                let currentPos;
                if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                    const currentPoint = gameState.pathPoints[enemy.pathIndex];
                    const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                    
                    // 计算当前位置百分比
                    const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                    const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                    currentPos = getPixelPosition({x, y});
                } else {
                    currentPos = getPixelPosition(gameState.pathPoints[gameState.pathPoints.length - 1]);
                }
                
                showBattleHint(currentPos.x, currentPos.y - 20, `+${enemy.reward}`, 'reward');
                
                updateStats();
                
                // 创建死亡粒子效果
                // 根据敌人类型设置粒子颜色
                let particleColor = '#B45309'; // 默认棕色
                if (enemy.type === 'taotie') particleColor = '#059669';
                else if (enemy.type === 'bifang') particleColor = '#DC2626';
                
                createParticles(
                    currentPos.x, currentPos.y, 15, 
                    particleColor,
                    [2, 5]
                );
                
                playSound('enemyDie');
            }
            
            gameState.enemies.splice(enemyIndex, 1);
        }
        
        // 检查是否所有敌人都被消灭
        if (gameState.enemies.length === 0 && gameState.isPlaying) {
            // 设置波次倒计时
            gameState.waveCountdown = 10;
            updateGameStatus();
            
            gameState.waveTimer = setInterval(() => {
                if (!gameState.isPlaying) {
                    clearInterval(gameState.waveTimer);
                    return;
                }
                
                gameState.waveCountdown--;
                updateGameStatus();
                
                if (gameState.waveCountdown <= 0) {
                    clearInterval(gameState.waveTimer);
                    gameState.waveTimer = null;
                    nextWave();
                }
            }, 1000);
            
            nextWaveButton.disabled = false;
            showNotification(`第${gameState.wave}波敌人已被击退！`, 'success');
        }
    }
    
    // 塔攻击敌人
    function towersAttack() {
        const now = Date.now();
        
        gameState.towers.forEach(tower => {
            // 检查攻击冷却
            if (now - tower.lastAttack < tower.speed) {
                return;
            }
            
            const towerType = towerTypes[tower.type];
            
            // 寻找范围内的敌人
            let target = null;
            let closestDistance = Infinity;
            
            gameState.enemies.forEach(enemy => {
                // 计算当前敌人位置
                let enemyPos;
                if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                    const currentPoint = gameState.pathPoints[enemy.pathIndex];
                    const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                    
                    // 计算当前位置百分比
                    const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                    const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                    enemyPos = {x, y};
                } else {
                    enemyPos = gameState.pathPoints[gameState.pathPoints.length - 1];
                }
                
                // 计算距离
                const dx = enemyPos.x - tower.x;
                const dy = enemyPos.y - tower.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                // 检查是否在范围内
                if (distance <= tower.range && distance < closestDistance) {
                    closestDistance = distance;
                    target = {enemy, position: enemyPos};
                }
            });
            
            // 如果有目标，进行攻击
            if (target) {
                tower.lastAttack = now;
                
                // 记录攻击效果
                gameState.attackEffects.push({
                    position: target.position,
                    createdAt: now,
                    towerType: tower.type
                });
                
                // 计算伤害（考虑抗性）
                let damage = tower.attack;
                if (target.enemy.resistances.includes(tower.type)) {
                    damage = Math.round(damage * 0.3); // 抗性减少70%伤害
                }
                
                // 记录总伤害
                gameStats.totalDamageDealt += damage;
                
                // 烽火台累计伤害统计
                if (tower.type === 'fire') {
                    towerTypes.fire.damageDealt += damage;
                    if (towerTypes.fire.damageDealt >= 1000 && 
                        !achievements.find(a => a.id === 'flame_master').unlocked) {
                        unlockAchievement('flame_master');
                    }
                }
                
                // 佛光塔穿透效果
                if (tower.type === 'light' && tower.level > 1) {
                    // 找到目标后方的其他敌人
                    const additionalTargets = gameState.enemies
                        .filter(e => e.id !== target.enemy.id)
                        .map(enemy => {
                            let enemyPos;
                            if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                                const currentPoint = gameState.pathPoints[enemy.pathIndex];
                                const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                                const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                                const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                                enemyPos = {x, y};
                            } else {
                                enemyPos = gameState.pathPoints[gameState.pathPoints.length - 1];
                            }
                            
                            // 计算与主目标的距离
                            const dx = enemyPos.x - target.position.x;
                            const dy = enemyPos.y - target.position.y;
                            const distance = Math.sqrt(dx * dx + dy * dy);
                            
                            return {enemy, distance, position: enemyPos};
                        })
                        .filter(t => t.distance < tower.range * 0.5)
                        .sort((a, b) => a.distance - b.distance)
                        .slice(0, Math.min(tower.level - 1, 2)); // 最多穿透2个目标
                        
                    // 对穿透目标造成伤害
                    additionalTargets.forEach(t => {
                        let pierceDamage = Math.round(damage * 0.6);
                        if (t.enemy.resistances.includes(tower.type)) {
                            pierceDamage = Math.round(pierceDamage * 0.3);
                        }
                        
                        t.enemy.health -= pierceDamage;
                        gameStats.totalDamageDealt += pierceDamage;
                        
                        // 记录穿透攻击效果
                        gameState.attackEffects.push({
                            position: t.position,
                            createdAt: now,
                            towerType: tower.type
                        });
                        
                        // 显示伤害提示
                        const pixelPos = getPixelPosition(t.position);
                        showBattleHint(pixelPos.x, pixelPos.y - 20, pierceDamage, 'damage');
                        
                        // 检查敌人是否死亡
                        if (t.enemy.health <= 0) {
                            // 增加金钱奖励
                            gameState.money += t.enemy.reward;
                            updateGameStatus();
                            
                            // 移除敌人
                            removeEnemy(t.enemy.id);
                        }
                    });
                }
                
                // 应用伤害
                target.enemy.health -= damage;
                
                // 显示伤害提示
                const pixelPos = getPixelPosition(target.position);
                showBattleHint(pixelPos.x, pixelPos.y - 20, damage, 'damage');
                
                // 八卦阵的减速效果
                if (tower.type === '八卦' && towerType.slow) {
                    target.enemy.slowFactor = Math.max(1 - towerType.slow, target.enemy.slowFactor);
                }
                
                // 烽火台的范围伤害
                if (tower.type === 'fire') {
                    // 找到范围内的其他敌人
                    const splashTargets = gameState.enemies
                        .filter(e => e.id !== target.enemy.id)
                        .map(enemy => {
                            let enemyPos;
                            if (enemy.pathIndex < gameState.pathPoints.length - 1) {
                                const currentPoint = gameState.pathPoints[enemy.pathIndex];
                                const nextPoint = gameState.pathPoints[enemy.pathIndex + 1];
                                const x = currentPoint.x + (nextPoint.x - currentPoint.x) * enemy.progress;
                                const y = currentPoint.y + (nextPoint.y - currentPoint.y) * enemy.progress;
                                enemyPos = {x, y};
                            } else {
                                enemyPos = gameState.pathPoints[gameState.pathPoints.length - 1];
                            }
                            
                            // 计算与主目标的距离
                            const dx = enemyPos.x - target.position.x;
                            const dy = enemyPos.y - target.position.y;
                            const distance = Math.sqrt(dx * dx + dy * dy);
                            
                            return {enemy, distance, position: enemyPos};
                        })
                        .filter(t => t.distance < tower.range * 0.3);
                        
                    // 对范围内敌人造成伤害
                    splashTargets.forEach(t => {
                        let splashDamage = Math.round(damage * 0.5);
                        if (t.enemy.resistances.includes(tower.type)) {
                            splashDamage = Math.round(splashDamage * 0.3);
                        }
                        
                        t.enemy.health -= splashDamage;
                        gameStats.totalDamageDealt += splashDamage;
                        
                        // 记录范围攻击效果
                        gameState.attackEffects.push({
                            position: t.position,
                            createdAt: now,
                            towerType: tower.type
                        });
                        
                        // 显示伤害提示
                        const pixelPos = getPixelPosition(t.position);
                        showBattleHint(pixelPos.x, pixelPos.y - 20, splashDamage, 'damage');
                        
                        // 检查敌人是否死亡
                        if (t.enemy.health <= 0) {
                            // 增加金钱奖励
                            gameState.money += t.enemy.reward;
                            updateGameStatus();
                            
                            // 移除敌人
                            removeEnemy(t.enemy.id);
                        }
                    });
                }
                
                playSound('enemyHit');
                
                // 检查敌人是否死亡
                if (target.enemy.health <= 0) {
                    // 连弩塔击杀统计
                    if (tower.type === 'crossbow') {
                        towerTypes.crossbow.killCount++;
                        if (towerTypes.crossbow.killCount >= 50 && 
                            !achievements.find(a => a.id === 'sniper').unlocked) {
                            unlockAchievement('sniper');
                        }
                    }
                    
                    // 增加金钱奖励
                    gameState.money += target.enemy.reward;
                    updateGameStatus();
                    showNotification(`获得 ${target.enemy.reward} 铜钱奖励`, 'info');
                    playSound('coinCollect');
                    
                    // 移除敌人
                    removeEnemy(target.enemy.id);
                }
                
                // 检查成就
                checkAchievements();
            }
        });
    }
    
    // 游戏主循环
    function gameLoop(timestamp) {
        updateEnemies();
        towersAttack();
        updateParticles();
        updateDecorativeElements();
        drawGame(timestamp); // 每帧重绘游戏
    }
    
    // 开始游戏
    function startGame() {
        gameState.isPlaying = true;
        gameOverlay.classList.add('hidden');
        spawnWave(gameState.wave);
        
        // 启动游戏循环
        gameState.gameLoop = setInterval(() => {
            gameLoop(Date.now());
        }, 30); // 每30ms更新一次（约33FPS）
        
        showNotification('战斗开始！建造防御塔抵御敌人进攻', 'info');
        playSound('click');
    }
    
    // 下一波
    function nextWave() {
        gameState.wave++;
        gameStats.highestWave = Math.max(gameStats.highestWave, gameState.wave);
        updateGameStatus();
        updateStats();
        spawnWave(gameState.wave);
        
        // 每3波增加一些金钱
        if (gameState.wave % 3 === 0) {
            const bonus = 200 * (gameConfig.difficulty === 'easy' ? 1.2 : 
                                 gameConfig.difficulty === 'hard' ? 0.8 : 1);
            gameState.money += bonus;
            updateGameStatus();
            showNotification(`每3波奖励！获得 ${bonus} 铜钱`, 'success');
            playSound('coinCollect');
        }
    }
    
    // 结束游戏
    function endGame(isVictory) {
        gameState.isPlaying = false;
        clearInterval(gameState.gameLoop);
        
        // 清除波次倒计时
        if (gameState.waveTimer) {
            clearInterval(gameState.waveTimer);
        }
        
        showGameResult(isVictory);
    }
    
    // 重新开始
    function restartGame() {
        // 清除游戏循环
        if (gameState.gameLoop) {
            clearInterval(gameState.gameLoop);
        }
        
        // 清除波次倒计时
        if (gameState.waveTimer) {
            clearInterval(gameState.waveTimer);
        }
        
        // 重置游戏状态
        gameState.money = 500;
        gameState.lives = 10;
        gameState.wave = 1;
        gameState.isPlaying = false;
        gameState.selectedTower = null;
        gameState.towers = [];
        gameState.enemies = [];
        gameState.currentEnemyId = 0;
        gameState.attackEffects = [];
        gameState.particles = [];
        gameState.waveTimer = null;
        gameState.waveCountdown = 0;
        
        // 重置塔类型统计
        for (const key in towerTypes) {
            if (towerTypes[key].killCount !== undefined) {
                towerTypes[key].killCount = 0;
            }
            if (towerTypes[key].damageDealt !== undefined) {
                towerTypes[key].damageDealt = 0;
            }
        }
        
        // 重置成就
        achievements.forEach(ach => {
            ach.unlocked = false;
        });
        gameStats.achievements = [];
        
        // 重置游戏统计
        gameStats.enemiesKilled = 0;
        gameStats.highestWave = 0;
        gameStats.towersBuilt = 0;
        gameStats.towersUpgraded = 0;
        gameStats.totalDamageDealt = 0;
        gameStats.coinsEarned = 0;
        gameStats.livesLost = 0;
        
        // 重置放置点
        towerPlaces.forEach(place => {
            place.classList.remove('tower-place-unavailable');
            place.classList.add('tower-place-available');
        });
        
        // 重置塔选择
        towerSelects.forEach(s => s.classList.remove('border-primary', 'bg-primary/10'));
        
        // 重置UI
        updateGameStatus();
        updateStats();
        towerInfo.style.display = 'none';
        overlayTitle.textContent = '准备战斗';
        overlayMessage.textContent = '点击开始按钮，抵御第一波敌人的进攻，守护长城防线';
        startButton.textContent = '开始战斗';
        gameOverlay.classList.remove('hidden');
        
        // 重绘游戏
        drawGame();
    }
    
    // 为塔添加点击事件
    canvas.addEventListener('click', function(e) {
        if (!gameState.isPlaying) return;
        
        const rect = canvas.getBoundingClientRect();
        const pixelPos = {
            x: e.clientX - rect.left,
            y: e.clientY - rect.top
        };
        const percentPos = getPercentPosition(pixelPos);
        
        // 检查是否点击了塔
        let clickedTower = null;
        gameState.towers.forEach(tower => {
            const dx = tower.x - percentPos.x;
            const dy = tower.y - percentPos.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance < 5) { // 点击范围
                clickedTower = tower;
            }
        });
        
        if (clickedTower) {
            showTowerInfo(clickedTower);
            playSound('click');
        } else {
            // 如果点击了其他地方，关闭塔信息
            towerInfo.classList.add('scale-95', 'opacity-0', 'pointer-events-none');
            setTimeout(() => {
                towerInfo.style.display = 'none';
            }, 300);
        }
    });
    
    // 开始按钮事件
    startButton.addEventListener('click', function() {
        if (gameConfig.tutorialEnabled && gameState.wave === 1 && gameStats.enemiesKilled === 0) {
            // 隐藏教程提示
            tutorialTooltip.classList.remove('show');
            // 开始游戏
            startGame();
            gameConfig.tutorialEnabled = false;
        } else {
            startGame();
        }
    });
    
    // 下一波按钮事件
    nextWaveButton.addEventListener('click', function() {
        if (!gameState.isPlaying || gameState.enemies.length > 0) return;
        
        nextWave();
        playSound('click');
    });
    
    // 重新开始按钮事件
    restartButton.addEventListener('click', function() {
        restartGame();
        playSound('click');
    });
    
    // 页面加载完成后初始化
    window.addEventListener('load', function() {
        // 绘制地图装饰
        drawMapDecorations();
        
        // 隐藏加载界面
        setTimeout(() => {
            loadingOverlay.style.opacity = '0';
            setTimeout(() => {
                loadingOverlay.remove();
                
                // 显示教程
                if (gameConfig.tutorialEnabled) {
                    setTimeout(startTutorial, 1000);
                }
            }, 500);
        }, 1500);
        
        // 初始化绘制
        drawGame();
    });
});